package com.qfmy.baseCode.builder;

import com.qfmy.baseCode.consts.PathAndPackageConst;
import com.qfmy.baseCode.utils.CommentUtils;
import com.qfmy.baseCode.utils.StringUtils;
import lombok.Cleanup;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author: 廖志伟
 * @date: 2024-11-25
 * 创建登入接口
 */
@Data
@Slf4j
@SuppressWarnings("all")
public class BuildLogin {
    //定义一个log日志对象
    private static final Logger log = LoggerFactory.getLogger(BuildLogin.class);
    //定义一个变量获取登入的路径
    private String loginPath;
    //定义一个基础包路径
    private String basePackage;
    //定义一个定义一个基础类路径
    private String basePath;
    //获取登入类的表名
    private String tableName;
    //定义一个注册的类型
    private String registerType;
    //导入公共的包
    private String commonPackage;
    //定义一个变量获取登入的方式
    private String loginType;
    //定义一个表的副本变量
    private String tableNameCopy;
    //定义一个pojo的包路径
    private String pojoPackage;
    //定义一个扩展类所在的包
    private String extendPackage;
    //定义一个扩展类的名称
    private String extendName;

    @Contract(pure = true)
    public BuildLogin(String loginPath, @NotNull String basePackage, String tableName, String registerType, String commonPackage, String loginType,String pojoPackage,String extendPackage,String extendName) {
        this.basePackage = basePackage;
        this.tableName = tableName;
        this.registerType = registerType;
        this.commonPackage = commonPackage;
        this.loginType = loginType;
        this.loginPath = loginPath;
        this.tableNameCopy = tableName;
        this.pojoPackage = pojoPackage;
        this.basePath = PathAndPackageConst.PATH_BASE + basePackage.replace(".", "/");
        this.extendPackage = extendPackage;
        this.extendName = extendName;
    }

    /**
     * 生成登入接口
     */
    @SneakyThrows
    public void execute(){
        //生成controller层代码
        builderController();
        //生成service层代码
        builderService();
        //生成serviceImpl层代码
        builderServiceImpl();
        //生成mapper层代码
        builderMapper();
    }



    /**
     * 生成controller层代码
     */
    @SneakyThrows
    private void builderController() {
        //创建一个文件夹
        File file = new File(basePath + "/controller");
        //判断文件夹是否存在，如果不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建一个StringBuilder对象
        StringBuilder sb = new StringBuilder();
        //对表名或者字段名进行处理
        String[] processName = tableName.split("_");
        //将表名或者字段名转换为大写
        String newName = StringUtils.firstCharToUpperCase(processName[0]);
        //把表名或者字段名添加到StringBuilder对象中
        sb.append(newName);
        //循环遍历processName数组
        for (int i = 1; i <processName.length; i++) {
            //将表名或者字段名转换为大写
           newName = StringUtils.firstCharToUpperCase(processName[i]);
            //把表名或者字段名添加到StringBuilder对象中
            sb.append(newName);
        }
        tableName = sb.toString();
        //创建登入controller的文件
        File folde = new File(file ,tableName + "Controller.java");
        //创建输出流对象
        @Cleanup  OutputStream out = new FileOutputStream(folde);
        @Cleanup  OutputStreamWriter ow = new  OutputStreamWriter(out);
        @Cleanup BufferedWriter bw =   new BufferedWriter(ow);
        //写入文件
        bw.write("package " + basePackage + ".controller;\n");
        bw.write("import org.springframework.web.bind.annotation.RestController;\n");
        bw.write("import org.springframework.web.bind.annotation.RequestMapping;\n");
        bw.write("import org.springframework.web.bind.annotation.GetMapping;\n");
        bw.write("import jakarta.annotation.Resource;\n");
        bw.write("import org.springframework.web.bind.annotation.PostMapping;\n");
        bw.write("import org.springframework.web.bind.annotation.RequestParam;\n");
        bw.write("import org.springframework.web.bind.annotation.RequestBody;\n");
        bw.write("import " + basePackage + "." + extendPackage + "." + tableName + "query;\n");
        bw.write("import " + commonPackage + "." +  "utils.Captcha;\n");
        bw.write("import " + basePackage + "." + pojoPackage+ "." + tableName + ";\n");
        bw.write("import " + commonPackage + ".result.*;\n");
        bw.write("import " + basePackage + ".service." + tableName + "Service;\n");


        //生成注释
        CommentUtils.CreateClassComment(bw,"生成登入controller类");
        bw.write("@RestController\n");
        bw.write("@RequestMapping(\"" + loginPath + "\")\n");
        bw.write("@SuppressWarnings({\"all\"})\n");
        bw.write("public class " + tableName + "Controller {\n");
        //生成注释
        CommentUtils.CreateFieldComment(bw,"注入" + tableName + "Service");
        bw.write("\t\t@Resource\n");
        bw.write("\t\tprivate " + tableName + "Service " + tableName.toLowerCase() + "Service;\n");
        //进行注册
        CommentUtils.CreateMethodComment("进行注册",bw);
        bw.write("\t\t@RequestMapping(\"/register\")\n");
        bw.write("\t\tpublic Result register(@RequestBody " + tableName + extendName + " " + tableName.toLowerCase() + extendName + ") {\n");
        bw.write("\t\t\t"+ tableName.toLowerCase() + "Service.register(" + tableName.toLowerCase() + extendName + ");\n");
        bw.write("\t\t\treturn Result.ok();\n");
        bw.write("\t\t}\n");
        //判断是否是邮箱注册
        if(registerType.equals("3"))
        {
            //发送邮箱验证码
            CommentUtils.CreateMethodComment("发送邮箱验证码",bw);
            bw.write("\t\t@GetMapping(value=\"/sendEmailCode\")\n");
            bw.write("\t\tpublic Result sendEmailCode(@RequestParam String email){\n");
            bw.write("\t\t\t" + tableName.toLowerCase() + "Service.sendEmailCode(email);\n");
            bw.write("\t\t\treturn Result.ok(\"成功发送\");\n");
        }

        //进行登入
        CommentUtils.CreateMethodComment("用户登入接口",bw);
        bw.write("\t\t@PostMapping\n");
        bw.write("\t\tpublic Result<String> login(@RequestBody " + tableName + extendName + " " + tableName.toLowerCase() + extendName + ") {\n");
        bw.write("\t\t\tString token = " + tableName.toLowerCase() + "Service.login(" + tableName.toLowerCase() + extendName + ");\n");
        bw.write("\t\t\treturn Result.ok(token);\n");
        bw.write("\t\t}\n");

        //获取图形验证码
        CommentUtils.CreateMethodComment("获取图形验证码",bw);
        bw.write("\t\t@GetMapping(value = \"/getCaptcha\")\n");
        bw.write("\t\tpublic Result<Captcha> getCaptcha(){\n");
        bw.write("\t\t\tCaptcha captcha = " + tableName.toLowerCase() + "Service.getCaptcha();\n");
        bw.write("\t\t\treturn Result.ok(captcha);\n");
        bw.write("\t\t}\n");

        //判断是不是手机号登入
        if(loginType.equals("2"))
        {
            //获取短信验证码
            CommentUtils.CreateMethodComment("获取短信验证码",bw);
            bw.write("\t\t@RequestMapping(\"/getSmsCode\")\n");
            bw.write("\t\tpublic Result getSmsCode(@RequestParam String phone){\n");
            bw.write("\t\t\t" + tableName.toLowerCase() + "Service.getSmsCode(phone);\n");
            bw.write("\t\t\treturn Result.ok();\n");
            bw.write("\t\t}\n");
        }
        //获取用户信息
        CommentUtils.CreateMethodComment("获取用户信息",bw);
        bw.write("\t\t@GetMapping(value = \"/getUserInfo\")\n");
        bw.write("\t\tpublic Result<"+tableName+ extendName + "> getUserInfo(){\n");
        bw.write("\t\t\t"+tableName+ extendName + " " + tableName.toLowerCase() + extendName + " = " + tableName.toLowerCase() + "Service.getUserInfo();\n");
        bw.write("\t\t\treturn Result.ok("+tableName.toLowerCase() + extendName + ");\n");
        bw.write("\t\t}\n");



        bw.write("}");

    }

    /**
     * 生成service层代码
     */
    @SneakyThrows
    private void builderService() {
        //创建一个文件夹
        File file = new File(basePath + "/service");
        //判断文件夹是否存在，如果不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建登入生成Service层文件
        File folde = new File(file, tableName + "Service.java");
        //创建输出流对象
        @Cleanup  OutputStream out = new FileOutputStream(folde);
        @Cleanup  OutputStreamWriter ow = new  OutputStreamWriter(out);
        @Cleanup BufferedWriter bw =   new BufferedWriter(ow);
        bw.write("package " + basePackage + ".service;\n");
        bw.write("import " + basePackage + "." + pojoPackage+ "." + tableName + ";\n");
        bw.write("import " + commonPackage + "." +  "utils.Captcha;\n");
        bw.write("import " + basePackage + "." + extendPackage + "." + tableName + "query;\n");
        //生成注释
        CommentUtils.CreateClassComment(bw,"生成" + tableName + "Service接口");
        bw.write("@SuppressWarnings({\"all\"})\n");
        bw.write("public interface " + tableName + "Service {\n");
        //生成方法注释
        CommentUtils.CreateMethodComment("进行注册", bw);
        bw.write("\t\tvoid register("+tableName + extendName + " " + tableName.toLowerCase() + extendName + ");\n");
        //生成方法注释
        CommentUtils.CreateMethodComment("进行登入", bw);
        bw.write("\t\tString login("+tableName + extendName + " "+ tableName.toLowerCase() + extendName + ");\n");
        //生成方法注释
        CommentUtils.CreateMethodComment("获取图形验证码", bw);
        bw.write("\t\tCaptcha getCaptcha();\n");
        //获取用户信息
        //生成方法注释
        CommentUtils.CreateMethodComment("获取用户信息", bw);
        bw.write("\t\t"+tableName+ extendName + " getUserInfo();\n");
        //判断是否有邮箱注册
        if(loginType.equals("3"))
        {
            //生成注释
            CommentUtils.CreateMethodComment("发送邮箱验证码", bw);
            bw.write("\t\tvoid sendEmailCode(String email);\n");
        }
        //判断是否有短信验证码
        if(loginType.equals("2"))
        {
            //生成注释
            CommentUtils.CreateMethodComment("获取短信验证码", bw);
            bw.write("\t\tvoid getSmsCode(String phone);\n");
        }
        bw.write("}\n");

    }

    /**
     * 生成mapper层代码
     */
    @SneakyThrows
    private void builderMapper() {
        //创建一个文件夹
        File file = new File(basePath + "/mapper");
        //判断文件夹是否存在，如果不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建登入mapper的文件
        File folde = new File(file, tableName + "Mapper.java");
        //创建输出流对象
        @Cleanup  OutputStream out = new FileOutputStream(folde);
        @Cleanup  OutputStreamWriter ow = new  OutputStreamWriter(out);
        @Cleanup BufferedWriter bw =   new BufferedWriter(ow);
        bw.write("package " + basePackage + ".mapper;\n");
        bw.write("import org.apache.ibatis.annotations.Mapper;\n");
        bw.write("import org.apache.ibatis.annotations.Select;\n");
        bw.write("import " + basePackage + "." + pojoPackage + "." + tableName + ";\n");

        //生成mapper代码;
        CommentUtils.CreateClassComment(bw,"生成" + tableName + "Mapper接口");
        bw.write("@Mapper\n");
        bw.write("@SuppressWarnings({\"all\"})\n");
        bw.write("public interface " + tableName + "Mapper<T,P> extends BaseMapper<T,P> {\n");
        CommentUtils.CreateMethodComment("根据用户名查询用户信息", bw);
        bw.write("\t\t@Select(\"select * from "+tableName+" where account=#{account}\")\n");
        bw.write("\t\t"+tableName + " selectByAccount(String account);\n");
        CommentUtils.CreateMethodComment("根据id查询用户信息", bw);
        bw.write("\t\t@Select(\"select * from "+tableName+" where id=#{id}\")\n");
        bw.write("\t\t"+tableName + " selectById(Integer id);\n");

        bw.write("}\n");


    }


    /**
     * 生成serviceImpl层代码
     */
    @SneakyThrows
    private void builderServiceImpl() {
        //创建一个文件夹
        File file = new File(basePath + "/service/impl");
        //判断文件夹是否存在，如果不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建登入Serviceimpl的文件
        File folde = new File(file , tableName + "ServiceImpl.java");
        //创建输出流对象
        @Cleanup  OutputStream out = new FileOutputStream(folde);
        @Cleanup  OutputStreamWriter ow = new  OutputStreamWriter(out);
        @Cleanup BufferedWriter bw =   new BufferedWriter(ow);
        //生成ServiceImpl
        bw.write("package " + basePackage + ".service.impl;\n");
        bw.write("import org.springframework.util.DigestUtils;\n");
        bw.write("import org.springframework.stereotype.Service;\n");
        bw.write("import jakarta.annotation.Resource;\n");
        bw.write("import org.jetbrains.annotations.NotNull;\n");
        bw.write("import com.wf.captcha.SpecCaptcha;\n");
        bw.write("import java.util.UUID;\n");
        bw.write("import java.util.Date;\n");
        bw.write("import org.springframework.beans.BeanUtils;\n");
        bw.write("import " + basePackage + "." + pojoPackage+ "." + tableName + ";");
        bw.write("import " + basePackage + ".service." + tableName + "Service;\n");
        bw.write("import " + basePackage + ".mapper." + tableName + "Mapper;\n");
        bw.write("import " + basePackage + "." + extendPackage + "." + tableName + "query;\n");
        bw.write("import " + commonPackage + ".result.*;\n");
        bw.write("import " + commonPackage + ".utils.JwtUtil;\n");
        bw.write("import " + commonPackage + ".exception.BaseException;\n");
        bw.write("import " + commonPackage + ".utils.*;\n");
        bw.write("import " + commonPackage + ".redis.*;\n");
        bw.write("import " + commonPackage + ".enmus.*;\n");
        bw.write("import " + commonPackage + ".constant.*;\n");
        //判断是否使用邮箱进行注册
        if(registerType.equals("3"))
        {
            bw.write("import org.springframework.mail.javamail.JavaMailSender;\n");
            bw.write("import org.springframework.mail.javamail.MimeMessageHelper;\n");
            bw.write("imoort " + commonPackage + ".email.*;\n");
        }
        if(loginType.equals("2"))
        {
            bw.write("import com.aliyun.dysmsapi20170525.Client;\n");
            bw.write("import com.aliyun.dysmsapi20170525.models.SendSmsRequest;\n");
        }
        //生成注释
        CommentUtils.CreateClassComment(bw,"生成" + tableName + "ServiceImpl实现类");
        bw.write("@Service\n");
        bw.write("@SuppressWarnings({\"all\"})\n");
        bw.write("public class " + tableName + "ServiceImpl implements "  + tableName + "Service {\n");
        //注入Mapper
        CommentUtils.CreateFieldComment(bw,"注入" + tableName + "Mapper");
        bw.write("\t\t@Resource\n");
        bw.write("\t\tprivate " + tableName + "Mapper " + tableName.toLowerCase() + "Mapper;\n");
        //判断是否值使用手机号进行验证
        if(loginType.equals("2"))
        {
            CommentUtils.CreateFieldComment(bw,"阿里云短信验证码");
            bw.write("\t\t@Resource\n");
            bw.write("\t\tprivate Client client;\n");
        }
        //注入邮箱发送
        if(loginType.equals("3"))
        {
            CommentUtils.CreateFieldComment(bw,"注入邮件发送器");
            bw.write("\t\t@Resource\n");
            bw.write("\t\tprivate JavaMailSender mailSender;\n");
            CommentUtils.CreateFieldComment(bw,"邮箱配置类");
            bw.write("\t\t@Resource\n");
            bw.write("\t\tprivate EmailProperties emailProperties;\n");
        }

        //注入redis的工具类
        CommentUtils.CreateFieldComment(bw,"注入redis工具类");
        bw.write("\t\t@Resource\n");
        bw.write("\t\tprivate RedisUtils redisUtils;\n");
        //生成方法
        CommentUtils.CreateMethodComment("进行注册", bw);
        bw.write("\t\t@Override\n");
        bw.write("\t\tpublic void register(@NotNull "+tableName + extendName + " " + tableName.toLowerCase() + extendName + ") {\n");
        //账号加密码
        if(registerType.equals("1"))
        {
            Register(bw,tableName,null);
        }
        //账号加 +密码+手机号
        else if(registerType.equals("2"))
        {
            Register(bw,tableName,null);
        }
        //账号加 +密码+邮箱
        else if(registerType.equals("3"))
        {
            Register(bw,tableName,tableName.toLowerCase() + ".getCode()");
        }


        //生成登录方法
        CommentUtils.CreateMethodComment("进行登录", bw);
        bw.write("\t\t@Override\n");
        bw.write("\t\tpublic String login("+tableName + extendName + " "+ tableName.toLowerCase() + extendName + "){\n");
        //判断登入的方式
        //账号加密码 + 图形验证码
        if(loginType.equals("1"))
        {
            bw.write("\t\t//判断验证码是否为空\n");
            bw.write("\t\tif(" + tableName.toLowerCase() + extendName + ".getCaptchaCode() == null){ \n");
            bw.write("\t\t\tthrow new BaseException(ResultCodeEnum.CAPTCHA_EMPTY);\n");
            bw.write("\t\t}\n");
            bw.write("\t\t\t//获取账号和密码\n");
            bw.write("\t\t\tString account = " + tableName.toLowerCase() + extendName + ".getAccount();\n");
            bw.write("\t\t\t//查询数据库的信息\n");
            bw.write("\t\t\t" + tableName + " loginUser"  + " = " + tableName.toLowerCase() + "Mapper.selectByAccount(account);\n");
            bw.write("\t\t\tif(loginUser"  + " == null){\n");
            bw.write("\t\t\t\tthrow new BaseException(ResultCodeEnum.LOGIN_CODE_EMPTY);\n");
            bw.write("\t\t\t}\n");
            bw.write("\t\t\t//判断验证码是否正确\n");
            bw.write("\t\t\tString captchaCode = (String)redisUtils.get(" + tableName.toLowerCase() + extendName + ".getCaptchaKey());\n");
            bw.write("\t\t//判断验证码是否过期\n");
            bw.write("\t\t\tif(captchaCode == null){\n");
            bw.write("\t\t\t\tthrow new BaseException(ResultCodeEnum. LOGIN_CODE_EXPIRED);\n");
            bw.write("\t\t\t}\n");
            bw.write("\t\t//判断验证码是否正确\n");
            bw.write("\t\t\tif(!captchaCode.equals(" + tableName.toLowerCase() + extendName + ".getCaptchaCode())){\n");
            bw.write("\t\t\t\tthrow new BaseException(ResultCodeEnum. LOGIN_CODE_ERROR);\n");
            bw.write("\t\t\t}\n");
            bw.write("\t\t\t//判断密码是否正确\n");
            bw.write("\t\t\tString password = " + tableName.toLowerCase() + extendName + ".getPassword();\n");
            bw.write("\t\t\t//进行加密\n");
            bw.write("\t\t\tpassword = DigestUtils.md5DigestAsHex(password.getBytes());");
            bw.write("\t\t\tif(!password.equals(loginUser"  + ".getPassword())){\n");
            bw.write("\t\t\t\tthrow new BaseException(ResultCodeEnum.ACCOUNT_PASSWORD);\n");
            bw.write("\t\t\t}\n");
            //获取token
            bw.write("\t\t\t//创建jwt令牌\n");
            bw.write("\t\t\tString token = JwtUtil.createToken(Long.valueOf(loginUser.getId()) , account);\n");
            //定义一个key
            bw.write("\t\t\tString key = \"token\";\n");
            bw.write("\t\t\t//将token存入redis中\n");
            bw.write("\t\t\tredisUtils.set(key,token,RedisConstant.LOGIN_TOKEN,\"h\");\n");
            bw.write("\t\t\treturn token;\n");
        }
        //手机号 + 短信验证码
        else if(loginType.equals("2"))
        {
            bw.write("\t\t//获取手机号\n");
            bw.write("\t\tString phone = " + tableName.toLowerCase() + extendName + ".getPhone();\n");
            bw.write("\t\t//获取验证码\n");
            bw.write("\t\tString code = " + tableName.toLowerCase() + extendName + ".getCode();\n");
            bw.write("\t\t//根据手机号去查找用户\n");
            bw.write("\t\t" + tableName + " user  = " + tableName + "Mapper.selectByPhone(phone);\n");
            bw.write("\t\tif(user == null){\n");
            bw.write("\t\t\tthrow new BaseException(ResultCodeEnum.LOGIN_PHONE_EMPTY);\n");
            bw.write("\t\t}\n");
            bw.write("\t\t//从redis里面获取验证码\n");
            if(loginPath.equals("/admin/login"))
            {
                bw.write("\t\tString redisCode = (String)rt.opsForValue().get(RedisConstant.ADMIN_LOGIN_PREFIX + phone);\n");
            }
           else{
                bw.write("\t\tString redisCode = rt.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);\n");
            }
           bw.write("\t\tif(redisCode == null){\n");
            bw.write("\t\t\tthrow new BaseException(ResultCodeEnum.LOGIN_CODE_EXPIRED);\n");
            bw.write("\t\t}\n");
            //获取token
            bw.write("\t\t//创建jwt令牌\n");
            bw.write("\t\tString token = JwtUtil.createToken(Long.valueOf("+tableName.toLowerCase()+ extendName + ".getId()) , "+tableName.toLowerCase()+".getAccount());\n");
            //定义一个key
            bw.write("\t\t\tString key = \"token\";\n");
            bw.write("\t\t\t//将token存入redis中\n");
            bw.write("\t\t\tredisUtils.set(key,token,RedisConstant.LOGIN_TOKEN,\"h\");\n");
            bw.write("\t\treturn token;\n");
        }
        //微信扫描登入
        else if(loginType.equals("3"))
        {

        }
        bw.write("\t\t}\n");

        if(loginType.equals("2"))
        {
            //调用获取短信验证码的方法
            getSsmCode(bw);
        }
        if(registerType.equals("3"))
        {
            //发送邮箱验证码
            SendEmail(bw,tableName);
            sendEmail(bw);
        }
        //获取图形验证码
        getCode(bw);
        //获取用户信息
        getUserInfo(bw,tableName);

        //结束标记
        bw.write("\t}\n");

    }

    /**
     * 获取用户信息
     * @param bw
     * @param tableName
     */
    @SneakyThrows
    public void getUserInfo(@NotNull BufferedWriter bw, @NotNull String tableName)
    {
        //获取用户信息
        CommentUtils.CreateMethodComment("获取用户信息", bw);
        bw.write("\t\t@Override\n");
        bw.write("\t\tpublic "+tableName+"query getUserInfo(){\n");
        bw.write("\t\t\t//从当前线程获取用户id\n");
        bw.write("\t\t\tLoginUser loginUser = LoginUserHolder.get();\n");
        bw.write("\t\tLong id = loginUser.get(\"userId\");\n");
        bw.write("\t\t\t//根据id查询用户信息\n");
        bw.write("\t\t\t"+tableName  + " "+tableName.toLowerCase()  + " = "+tableName.toLowerCase()+"Mapper.selectById(id);\n");
        bw.write("\t\t//创建扩展对象\n");
        bw.write("\t\t" +tableName+ extendName + ""  + tableName.toLowerCase() + extendName + " = new "+tableName + extendName + "();\n");
        bw.write("\t\t//将用户信息赋值给扩展对象\n");
        bw.write("\t\tBeanUtils.copyProperties("+tableName.toLowerCase()+","+tableName.toLowerCase() + extendName + ");\n");
        bw.write("\t\t\treturn "+tableName.toLowerCase() + extendName + ";\n");
        bw.write("\t\t}\n\n");
    }

    /**
     * 发送邮箱验证码
     * @param bw
     * @param tableName
     */
    @SneakyThrows
    private void SendEmail(@NotNull BufferedWriter bw, @NotNull String tableName) {
        CommentUtils.CreateMethodComment("发送邮箱验证码", bw);
        bw.write("\t\tpublic void sendEmail(@NotNull String email ){\n");
        //根据邮箱去查询用户
        bw.write("\t\t//根据邮箱取查用户\n");
        bw.write("\t\t" + tableName + " emailUser = " + tableName.toLowerCase() + "Mapper.selectByEmail(email);\n");
        bw.write("\t\t//判断用户是否存在\n");
        bw.write("\t\tif(emailUser == null){\n");
        bw.write("\t\t\t//用户不存在\n");
        bw.write("\t\t\tthrow new BaseException(ResultCodeEnum.ACCOUNT_EXIST_ERROR);\n");
        bw.write("\t\t}\n");
        //用户存在
        bw.write("\t\t//发送邮箱验证码\n");
        bw.write("\t\tsendEmail(emailUser.getEmail(),\"1\",null);\n");
        bw.write("\t\t}\n\n");
    }

    /**
     * 发送邮箱
     * @param bw
     */
    @SneakyThrows
    public void sendEmail(@NotNull BufferedWriter bw)
    {
       bw.write("\t\tpublic void sendEmail(String email){\n");
        bw.write("\t\t//用户存在\n");
        bw.write("\t\t//生成验证码\n");
        bw.write("\t\tString code = CodeUtil.getCode(6);\n");
        bw.write("\t\t//发送邮箱验证码\n");
        bw.write("\t\tsendEmail(emailUser.getEmail(),code);\n");
        bw.write("\t\t//创建邮箱发送器");
        bw.write("\t\tMimeMessage mimeMessage = mailSender.createMimeMessage();\n");
        bw.write("\t\t//创建一个邮件信息帮助类\n");
        bw.write("\t\tMimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);\n");
        bw.write("\t\t//设置邮发送人\n");
        bw.write("\t\thelper.setFrom(emailProperties.getUsername());\n");
        bw.write("\t\t//设置收件人\n");
        bw.write("\t\thelper.setTo(email);\n");
        bw.write("\t\t//创建邮箱信息类\n");
        bw.write("\t\tSysSettingEmail sysSettingEmail = new EmailContext();\n");
        bw.write("\t\t//判断是否是注册\n");
        bw.write("\t\t\t\t//设置邮箱标题\n");
        bw.write("\t\t\tsysSettingEmail.setTitle(\"注册验证码\");\n");
        bw.write("\t\t\t//设置邮箱内容\n");
        bw.write("\t\t\tsysSettingEmail.setContent(\"您的验证码为:code,请在10分钟内完成验证");
        bw.write("\t\t//设置邮箱标题\n");
        bw.write("\t\thelper.setSubject(sysSettingEmail.getTitle());\n");
        bw.write("\t\t//设置邮箱内容\n");
        bw.write("\t\thelper.setText(sysSettingEmail.getContent(),code);\n");
        bw.write("\t\t//设置发送时间\n");
        bw.write("\t\thelper.setSentDate(new Date());\n");
        bw.write("\t\t//发送邮箱\n");
        bw.write("\t\tmailSender.send(mimeMessage);\n");
       bw.write("\t\t}");
    }


    /**
     * 进行注册的逻辑
     * @param bw
     * @param tableName
     */
    @SneakyThrows
    public void Register(@NotNull BufferedWriter bw, @NotNull String tableName,String code)
    {
        bw.write("\t\t//判断验证码是否为空\n");
        bw.write("\t\tif(" + tableName.toLowerCase() + extendName + ".getCaptchaCode() == null){ \n");
        bw.write("\t\t\tthrow new BaseException(ResultCodeEnum.CAPTCHA_EMPTY);\n");
        bw.write("\t\t}\n");
        bw.write("\t\t\t//判断验证码是否正确\n");
        bw.write("\t\t\tString captchaCode = (String)redisUtils.get(" + tableName.toLowerCase() + extendName + ".getCaptchaKey());\n");
        bw.write("\t\t//判断验证码是否过期\n");
        bw.write("\t\t\tif(captchaCode == null){\n");
        bw.write("\t\t\t\tthrow new BaseException(ResultCodeEnum. LOGIN_CODE_EXPIRED);\n");
        bw.write("\t\t\t}\n");
        bw.write("\t\t//判断验证码是否正确\n");
        bw.write("\t\t\tif(!captchaCode.equals(" + tableName.toLowerCase() + extendName + ".getCaptchaCode())){\n");
        bw.write("\t\t\t\tthrow new BaseException(ResultCodeEnum. LOGIN_CODE_ERROR);\n");
        bw.write("\t\t\t}\n");
        //判断是否值邮箱注册
        if(tableName.equals("3"))
        {
            bw.write("\t\t//从redis中获取验证码\n");
            bw.write("\t\tSysSettingEmail sysSettingEmail = (SysSettingEmail)redisUtils.get(\"email:code\");\n");
            bw.write("\t\tString content = sysSettingEmail.getContent();\n");
            bw.write("\t\t//截取邮箱验证码\n" +
                    "\t\t\tString redisCode = content.substring(content.indexOf(\":\"), content.indexOf(\",\"));");
            bw.write("\t\t//判断验证码是否正确\n");
            bw.write("\t\tif(!code.equals(redisCode))\n");
            bw.write("\t\t{\n");
            bw.write("\t\t\t//验证码错误\n");
            bw.write("\t\t throw new RuntimeException(ResultCodeRnum. LOGIN_CODE_ERROR);\n");
            bw.write("\t\t}\n");
        }
        bw.write("\t\t//创建登入的对象\n");
        bw.write("\t\t" + tableName + " " + tableName.toLowerCase() + " = new " + tableName + "();\n");
        bw.write("\t\t//将对象拷贝\n");
        bw.write("\t\tBeanUtils.copyProperties(" + tableName.toLowerCase() + extendName + ", " + tableName.toLowerCase() + ");\n");
        bw.write("\t\t\t//获取密码\n");
        bw.write("\t\t\tString password = " + tableName.toLowerCase() + extendName + ".getPassword();\n");
        bw.write("\t\t\t//进行加密\n");
        bw.write("\t\t\tpassword = DigestUtils.md5DigestAsHex(password.getBytes());\n");
        bw.write("\t\t\t" + tableName.toLowerCase()+ ".setPassword(password);\n");
        //设置时间
        bw.write("\t\t\t" + tableName.toLowerCase() + ".setCreateTime(new Date());\n");
        //设置更新时间
        bw.write("\t\t\t" + tableName.toLowerCase() + ".setUpdateTime(new Date());\n");
        bw.write("\t\t\t//进行注册\n");
        bw.write("\t\t\t" + tableName.toLowerCase() + "Mapper.insert(" + tableName.toLowerCase() + ");\n");
        bw.write("\t\t}\n");
    }


    /**
     * 定义一个类用来编写短信验证码的逻辑
     */
    @SneakyThrows
    public void SmsCode(@NotNull BufferedWriter bw)
    {
        CommentUtils.CreateMethodComment("获取阿里云短信验证码", bw);
        bw.write("\t\t@SneakyThrows\n");
        bw.write("\t\tpublic void sendCode(String phone, String code)\n");
        bw.write("\t\t{\n");
        bw.write("\t\t\t// 创建短信发送请求对象\n");
        bw.write("\t\t\tSendSmsRequest sendSmsRequest = new SendSmsRequest();\n");
        bw.write("\t\t\t // 设置接收验证码的手机号码\n");
        bw.write("\t\t\t // 设置短信签名名称\n");
        bw.write("\t\t  sendSmsRequest.setSignName(\"阿里云短信测试\");\n");
        bw.write("\t\t\t // 设置短信模板编号\n");
        bw.write("\t\t  sendSmsRequest.setTemplateCode(\"SMS_154950909\");\n");
        bw.write("\t\t\t // 设置短信模板参数，将验证码作为参数传入\n");
        bw.write("\t\t sendSmsRequest.setTemplateParam(\"{\\\"code\\\":\\\"\" + code + \"\\\"}\");\n");
        bw.write("\t\t\t // 发送短信\n");
        bw.write("\t\t client.sendSms(sendSmsRequest);\n");
        bw.write("\t\t}\n");
    }

    /**
     * 定义一个方法用来获取短信验证码
     * @param bw
     */
    @SneakyThrows
    public void getSsmCode(@NotNull BufferedWriter bw)
    {
        //生成注释
        CommentUtils.CreateMethodComment("使用手机号进行登入", bw);
        bw.write("\t\t@SneakyThrows\n");
        bw.write("\t\t@Override\n");
        bw.write("\t\tpublic void getSmsCode(String phone){\n");
        bw.write("\t\t//获取短信验证码\n");
        bw.write("\t\t String code = CodeUtils.getCode(6);\n");
        bw.write("\t\t//将验证码存放到redis\n");
        if(loginPath.equals("/app/login"))
        {
            bw.write("\t\tString key = RedisConstant.APP_LOGIN_PREFIX + phone;");
        }
        else if(loginPath.equals("/admin/login"))
        {
            bw.write("\t\tString key = RedisConstant.ADMIN_LOGIN_PREFIX + phone;");
        }
        bw.write("\t\tRedisTemplate<String,String> rt = redisUtils.getRedisTemplate();\n");
        bw.write("\t\t//限制验证码发送频率\n");
        bw.write("\t\tBoolean b = rt.hasKey(key);\n");
        bw.write("\t\tif(b){\n");
        bw.write("\t\t//获取验证码发送时间\n");
        bw.write("\t\tLong time = rt.getExpire(key, TimeUnit.SECONDS);\n");
        bw.write("\t\t//计算时间差\n");
        bw.write("\t\tLong diff = time - 60;\n");
        bw.write("\t\t//如果时间差小于60秒，则抛出异常\n");
        bw.write("\t\tif(diff < 60){\n");
        bw.write("\t\t\tthrow new BaseException(ResultCodeEnum.SEND_SMS_TOO_OFTEN);\n");
        bw.write("\t\t\t}\n");
        bw.write("\t\t}\n");
        bw.write("\t\t//通过短信发送验证码\n");
        bw.write("\t\tsendCode(phone, code);\n");
        bw.write("\t\t//将验证码存入redis\n");
        bw.write("\t\tredisUtils.set(key,code,RedisConstant.LOGIN_CODE_TTL_SEC,\"s\")\n");
        bw.write("\t\t}\n");
        //调用短信验证码的方法
        SmsCode(bw);
    }

    /**
     * 获取图形验证码
     * @param bw
     */
    @SneakyThrows
    public void getCode(@NotNull BufferedWriter bw){
        //获取图形验证码
        CommentUtils.CreateMethodComment("获取图形验证码", bw);
        bw.write("\t\t@Override\n");
        bw.write("\t\tpublic Captcha getCaptcha(){\n");
        bw.write("\t\t//创建一个验证码\n");
        bw.write("\t\tSpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);\n");
        bw.write("\t\tString code = specCaptcha.text().toLowerCase();\n");
        bw.write("\t\t//设置验证码存放在redis类名的值\n");
        if(loginPath.equals("/admin/login"))
        {
            bw.write("\t\tString key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();\n");
        }
        else
        {
            bw.write("\t\tString key = RedisConstant.APP_LOGIN_PREFIX + UUID.randomUUID();\n");
        }
        bw.write("\t\t//存入redis\n");
        bw.write("\t\tredisUtils.set(key,code,RedisConstant.LOGIN_CODE_TTL_SEC,\"s\");\n");
        bw.write("\t\treturn new Captcha(specCaptcha.toBase64(),key);\n");
        bw.write("\t}\n");
    }



}
